package com.flute.icrawler.framework.autoadjust;

/**
 * 一个标识符控制器，按照interval的频率自动把标识符设置为true.
 * 实现了IAdjustable接口，可以增加或者减少interval用作调整
 * 
 * @author Dave Yang
 * 
 */
/**
 * @author Administrator
 * 
 */
public class AbleTimer implements IAdjustable {
	/**
	 * 自动改变值的频率
	 */
	private int interval;

	/**
	 * 标识符
	 */
	private boolean able;

	private boolean isFinished = false;

	public AbleTimer(int interval) {
		this.interval = interval;
		run();
	}

	public void setFinished(boolean isFinished) {
		this.isFinished = isFinished;
	}

	public void setAble(boolean able) {
		this.able = able;
	}

	public boolean isAble() {
		return able;
	}

	@Override
	public void decrease() {
		synchronized (this) {
			interval--;
		}
	}

	@Override
	public void increase() {
		synchronized (this) {
			interval++;
		}
	}

	/**
	 * 启动后台线程来控制自动设置值
	 */
	private void run() {
		Thread th = new Thread(getRunnable());
		th.setName(this.getClass().getSimpleName());
		th.setDaemon(true);
		th.start();
	}

	private Runnable getRunnable() {
		return new Runnable() {
			@Override
			public void run() {
				while (!isFinished) {
					able = true;
					try {
						Thread.sleep(interval);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
	}

	public int getInterval() {
		return interval;
	}

	public void setInterval(int interval) {
		this.interval = interval;
	}

	@Override
	public int getCount() {
		return interval;
	}
}
